<?php
namespace Framework;


use App\Services\UploadService;
use Illuminate\Redis\Connections\PhpRedisConnection;
use Illuminate\Support\Facades\Redis;
use SimpleSoftwareIO\QrCode\BaconQrCodeGenerator;

class Hope
{
    public static function isProduct(): bool
    {
        $env = env('APP_ENV', 'prod');
        if ($env === 'prod') {
            return true;
        }
        return false;
    }

    public static function getRedis(string $connection = 'default'): PhpRedisConnection
    {
        /** @var PhpRedisConnection $redis */
        $redis = Redis::connection($connection);
        return $redis;
    }

    public static function getLoginId(): int
    {
        $jwt = app(Jwt::class);
        $user_id = $jwt->checkToken();
        if ($user_id === false) {
            return 0;
        }

        return $user_id;
    }

    /**
     * 获取随机邀请码
     * @return string
     */
    public static function makeInviterCode() {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0,25)]
            .strtoupper(dechex(date('m')))
            .date('d').substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf('%02d',rand(0,99));
        for(
            $a = md5( $rand, true ),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
            $d = '',
            $f = 0;
            $f < 6;
            $g = ord( $a[ $f ] ),
            $d .= $s[ ( $g ^ ord( $a[ $f + 6 ] ) ) - $g & 0x1F ],
            $f++
        );
        return $d;
    }

    /**
     * 创建二维码
     * @param $inviterCode
     * @return string
     */
    public static function makeInviterQrcode($inviterCode)
    {
        $text = "https://a.app.qq.com/o/simple.jsp?pkgname=com.ghhm.cooperation";
        $size = 200;
        //$img = public_path('/logo.png');
        $qr   = new BaconQrCodeGenerator();
        $img  = $qr->format('png')->size($size)->margin(1)->generate($text);
        $type = 'qrcode';
        $path = app(UploadService::class)->uploadQiniu($img,$type,$inviterCode);
        return $path;
    }

    /**
     * @param string $prefix
     * @return string
     */
    public static function random_order($prefix='MC')
    {
        return $prefix . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
    }

    public static function validatePhone($value)
    {
        $rule = '/^13\d{9}$|^14\d{9}$|^15\d{9}$|^16\d{9}$|^17\d{9}$|^18\d{9}|^19\d{9}$/';

        if (empty($value) || !preg_match($rule, $value)) {
            return false;
        }
        return true;
    }
    public static function name_auth($name,$id_card){
        $host = "https://idcert.market.alicloudapi.com";
        $path = "/idcard";
        $method = "GET";
        $appcode = "44bd084a52104adca116397a8c8b49d0";//开通服务后 买家中心-查看AppCode
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "idCard={$id_card}&name=".urlencode($name);

        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $out_put = curl_exec($curl);

        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        list($header, $body) = explode("\r\n\r\n", $out_put, 2);

        if ($httpCode == 200) {
            return $body;
        }
    }
    public static function get_sign($params, $sign_key)
    {
        //按字典序排序参数
        ksort($params);
        //$code = http_build_query($params);
        $array = [];
        foreach ($params as $key => $val){
            $val = is_array($val) ? json_encode($val) : $val;
            $array[] = $key . '=' . $val;
        }
        $code = implode('&',$array);
        //拼接密钥
        $code .= '&sign_key=' . $sign_key . 'jieao';

        //MD5加密
        $code = md5($code);
        //所有字符转为大写
        $result = strtoupper($code);
        return $result;
    }

    /**
     * http curl.
     * @param       $url
     * @param null  $data
     * @param array $headers
     *
     * @return bool|string
     */

    public static function http_request($url, $data = null, $headers = [])
    {
        $curl = curl_init();
        if (count($headers) >= 1)
        {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_URL, $url);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data))
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);

        return $output;
    }
    /**
     * String padding
     * @param $str
     *
     * @return string
     */
    public static function pkcs5Str($str, $len = 16) {

        if (strlen($str) >= 16) {
            $str = substr($str, 0, 16);
            $res = 0;
        } else {
            $res = $len - (strlen($str) % $len);
        }

        return $str . str_repeat(chr($res), $res);

    }

    /**
     * RSA数据加密解密
     * @param type $d
     * @param type $t encode加密  decode解密
     */
    public static function RSA_openssl($d, $t = 'encode', $sign = 'cmb') {
        if (empty($d)) {
            return 'data参数不能为空';
        }
        if (is_array($d)) {
            return 'data参数不能是数组形式';
        }

        switch ($sign) {
            case "cmbr":
                $rsa_public = config('app.cmb.public_rsa_decode_key');
                $rsa_private = config('app.cmb.private_rsa_decode_key');
                break;
            case "cmb":
            default:
                $rsa_public = config('app.cmb.public_rsa_key');
                $rsa_private = config('app.cmb.private_rsa_key');
                break;
        }

        if(empty($rsa_public)) {
            $rsa_public = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCl8UO7xMlNuvN/w9O4obcR2f7G
WlLzgIF3i9kO4vxYyYT6QD6f6RSztz6BRnODFLkPFzp+noMByKSvEZ6mz+j3au+d
TE+NuKpv0K+IlBC/97PKmDY/upSTeox1SoVJNRFGaSBB/GATNhSq+15+HL1Ih633
brlmQ+hrQQDlX+wHLwIDAQAB
-----END PUBLIC KEY-----';
        }
        if(empty($rsa_private)) {
            $rsa_private = '-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKXxQ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MBAAECgYBr+TQhwbjdqs3D+Ek7ZK81a7zjFEnlCZkMYpHWXkLjOe1ofrt29eE2sEN90QhQgoQHJAPx5XXmQMbDSe9zeRop8Nv595ScxKCwsXLTGPEikZHY6batPFXyo+PDhqIsCGJVwXEtcA6dih+47uVGHj0DWlgvAdl7DLtlWMB25o38OQJBAPvucmg857LgUrq4xXzGKj84ji5DDz5JZaqa/ppqzMBQeZt8x69ZjNvZjZyBkpIOe5POFLLZ1P1uz2ZtcDwFOs8CQQDqExFzwNrbBfxVm3/WldjoysDR0lW/ot2jWhJJDNNBjL38tUwesBStutLmu8foX0fN2577LDThzxw7pt/xkTx9AkAjDPPB6OdbjbY04EwppfBux1GQwie2xMNuTw4pMb626vtgVKX7kXv1gnkfUy+vPnCXCc77ay8k62vTllpNH3UlAkAJnWbmHlHfFUvcKFsD8XvLdCifdchX6tS31QdTQNecpa9YJgpOaGUxDa+EEsqPXPqSFiddod86N0utl5kzTwfxAkEAgTgXZmt+1NtJv/tQXs54m0xUtDHWcb3GjBdrzU4unwNCFsEbS0ympJP9m5AFJFuC/4+kTyr1pwqwSIfWAPNnNQ==
-----END PRIVATE KEY-----';
        }

        // decode
        if ($t == 'decode') {
            $private_key = openssl_pkey_get_private($rsa_private);
            if (!$private_key) {
                return('私钥不可用');
            }
            $return_de = openssl_private_decrypt(base64_decode($d), $decrypted, $private_key);
            if (!$return_de) {
                return('解密失败,请检查RSA秘钥');
            }
            return $decrypted;
        }

        // encode
        $key = openssl_pkey_get_public($rsa_public);
        if (!$key) {
            return('公钥不可用');
        }

        //openssl_public_encrypt 第一个参数只能是string
        //openssl_public_encrypt 第二个参数是处理后的数据
        //openssl_public_encrypt 第三个参数是openssl_pkey_get_public返回的资源类型
        $return_en = openssl_public_encrypt($d, $crypted, $rsa_public);
        if (!$return_en) {
            return('加密失败,请检查RSA秘钥');
        }

        return base64_encode($crypted);
    }
}
